package com.jk.garden1.controller;

import com.google.zxing.WriterException;
import com.jk.garden1.util.QRcodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Objects;

@RestController
@RequestMapping("/qr-code")
@Slf4j
public class QRCodeController {

    public static String url = "https://www.baidu.com/";


    /**
     * 方法一：响应文件流
     *
     * @return ResponseEntity响应文件流
     */
//    @GetMapping("methodOne")
//    public ResponseEntity<byte[]> methodOne() {
//        byte[] qrCode = null;
//        try {
//            qrCode = QRcodeUtil.generateQrCodeByte(url, 350, 350);
//        } catch (Exception e) {
//            log.info("Exception:{}", e.getMessage());
//        }
//        // Header设置文件类型（对于ResponseEntity响应的方式，必须设置文件类型）
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.IMAGE_PNG);
//
//        return new ResponseEntity<>(qrCode, headers, HttpStatus.CREATED);
//    }

    /**
     * 方法二：响应文件流
     *
     * @param response response原生响应文件流
     */
    @GetMapping("methodTwo")
    public void methodTwo(HttpServletResponse response) throws IOException {
        byte[] qrCode = null;
        try {
            qrCode = QRcodeUtil.generateQrCodeByte(url, 350, 350);
        } catch (Exception e) {
            log.info("Exception:{}", e.getMessage());
        }
        // Header设置文件类型（ContentType不设置也没事）
        response.setContentType(MediaType.IMAGE_PNG_VALUE);
        response.getOutputStream().write(Objects.requireNonNull(qrCode));
    }

    /**
     * 方法三：下载到本地
     *
     */
    @GetMapping("methodThree")
    public void methodThree() throws IOException, WriterException {
        //下载路径及文件名
        String filePath = "D:\\or-code.png";
        QRcodeUtil.generateQrCodeImage(url, 120, 120, filePath);
    }




}
